package com.github.xaidanwang.auth.server.handler;

import com.alibaba.fastjson.JSON;
import com.github.xaidanwang.auth.server.biz.UserBiz;
import com.github.xaidanwang.auth.server.config.JwtConfigPo;
import com.github.xaidanwang.auth.server.entity.UserInfo;
import com.github.xaidanwang.auth.server.util.JWTHelper;
import com.github.xaidanwang.auth.server.util.RedisUtil;
import com.github.xaidanwang.response.CommonResult;
import com.github.xaidanwang.response.ConstantEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author wang yi fei
 * @date 2019/10/6 13:48
 */
@Slf4j
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

	@Autowired
	private UserBiz userBiz;
	@Autowired
	private RedisUtil redisUtil;
	@Autowired
	JwtConfigPo jwtConfigPo;

	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
		UserInfo userInfo = userBiz.getUserInfoByUserName(authentication.getName());
		response.setHeader("Content-Type", "application/json;charset=utf-8");
		try {
			String token = JWTHelper.generateToken(userInfo,jwtConfigPo.getSignKey(),jwtConfigPo.getExpire());
			CommonResult commonResult = CommonResult.buildWithData(ConstantEnum.GLOBAL_SUCCESS,token);
			String  result = JSON.toJSONString(commonResult);
			response.setStatus(200);
			response.getWriter().write(result,0,result.length());

			//  缓存 jwt token
			redisUtil.cacheToken(token,userInfo,jwtConfigPo.getExpire());
		} catch (Exception e) {
			log.error("jwt 生成 token 失败,[{}]",e);
		}
	}
}
